package cn.iocoder.yudao.module.research.service.syslog;

import ch.qos.logback.core.util.NetworkAddressUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.net.Ipv4Util;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.research.controller.admin.syslog.vo.SyslogAnalysisRespVO;
import cn.iocoder.yudao.module.research.controller.admin.syslog.vo.SyslogPageReqVO;
import cn.iocoder.yudao.module.research.controller.admin.syslog.vo.SyslogSaveReqVO;
import cn.iocoder.yudao.module.research.dal.dataobject.alert.AlertDO;
import cn.iocoder.yudao.module.research.dal.dataobject.syslog.SyslogDO;
import cn.iocoder.yudao.module.research.dal.mysql.alert.AlertMapper;
import cn.iocoder.yudao.module.research.dal.mysql.syslog.SyslogMapper;
import cn.iocoder.yudao.module.research.service.alert.ChatService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.research.enums.ErrorCodeConstants.SYSLOG_CONTENT_EMPTY;
import static cn.iocoder.yudao.module.research.enums.ErrorCodeConstants.SYSLOG_NOT_EXISTS;

/**
 * syslog Service 实现类
 *
 * @author cai
 */
@Slf4j
@Service
@Validated
public class SyslogServiceImpl implements SyslogService {

    @Resource
    private SyslogMapper syslogMapper;

    @Resource
    private ChatService chatService;

    @Resource
    private AlertMapper alertMapper;

    @Override
    public Long createSyslog(SyslogSaveReqVO createReqVO) {
        // 插入
        SyslogDO syslog = BeanUtils.toBean(createReqVO, SyslogDO.class);
        syslog.setStatus(CommonStatusEnum.ENABLE.getStatus());
        syslogMapper.insert(syslog);
        // 返回
        return syslog.getId();
    }

    @Override
    public void updateSyslog(SyslogSaveReqVO updateReqVO) {
        // 校验存在
        validateSyslogExists(updateReqVO.getId());
        // 更新
        SyslogDO updateObj = BeanUtils.toBean(updateReqVO, SyslogDO.class);
        syslogMapper.updateById(updateObj);
    }

    @Override
    public void deleteSyslog(Long id) {
        // 校验存在
        validateSyslogExists(id);
        // 删除
        syslogMapper.deleteById(id);
    }

    private void validateSyslogExists(Long id) {
        if (syslogMapper.selectById(id) == null) {
            throw exception(SYSLOG_NOT_EXISTS);
        }
    }

    @Override
    public SyslogDO getSyslog(Long id) {
        return syslogMapper.selectById(id);
    }

    @Override
    public PageResult<SyslogDO> getSyslogPage(SyslogPageReqVO pageReqVO) {
        return syslogMapper.selectPage(pageReqVO);
    }

    @Override
    public String analysisSyslog(Long id) {
        SyslogDO syslog = syslogMapper.selectById(id);
        if (syslog == null) {
            throw exception(SYSLOG_NOT_EXISTS);
        } else if (StringUtils.isBlank(syslog.getContent())) {
            throw exception(SYSLOG_CONTENT_EMPTY);
        }
        String resp = chatService.analysisSyslog(syslog.getContent());
        String result = "";
        if (JsonUtils.isJson(resp)) {
            SyslogAnalysisRespVO respVO = JsonUtils.parseObject(resp, SyslogAnalysisRespVO.class);
            if (respVO.getAttackStatus()) {
                result = "存在攻击行为：" + respVO.getAttackName();
                AlertDO alert = new AlertDO();
                alert.setUrl(respVO.getUrl());
                if (StringUtils.isNotBlank(respVO.getActTime())) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    // 将字符串转换为LocalDateTime
                    LocalDateTime localDateTime = LocalDateTime.parse(respVO.getActTime(), formatter);
                    alert.setAlertTime(localDateTime);
                }
                alert.setThreatName(respVO.getAttackName());
                if (StringUtils.isNotBlank(respVO.getAttackLevel())) {
                    switch (respVO.getAttackLevel()) {
                        case "高危":
                            alert.setThreatLevel("30");
                            break;
                        case "中危":
                            alert.setThreatLevel("20");
                            break;
                        case "低危":
                            alert.setThreatLevel("10");
                            break;
                        default:
                            break;
                    }
                }
                alert.setSourceIp(respVO.getSourceIp());
                if (StringUtils.isNotBlank(respVO.getSourceIp())) {
                    alert.setSourceIpLong(Ipv4Util.ipv4ToLong(respVO.getSourceIp()));
                }
                alert.setSourcePort(respVO.getSourcePort());
                alert.setStatus(CommonStatusEnum.ENABLE.getStatus());
                alert.setSyslogId(id);
                alert.setAttackType(respVO.getAttackType());
                alert.setAnalyzeStep(respVO.getAnalyzeStep());
                alert.setAttackStatus(1);
                alertMapper.insert(alert);
            } else {
                result = "非攻击：" + respVO.getAttackName();
            }
        } else {
            result = "分析结果：" + resp;
        }
        syslog.setAiResponse(resp);
        syslogMapper.updateById(syslog);
        return result;
    }

}